package com.tankgame.models;

import com.tankgame.utils.Constants;
import com.tankgame.utils.Directions;

import java.awt.*;

public class Missile implements Runnable {
    private final Color color;
    private final Directions direction;
    private final int speed;
    private int x;
    private int y;
    private boolean isAlive;

    public Missile(int x, int y, Color color, Directions direction, int speed) {
        this.x = x;
        this.y = y;
        this.color = color;
        this.direction = direction;
        this.speed = speed;
        this.isAlive = true;
    }


    public void move() {
        switch (direction) {
            case UP:
                y -= speed;
                break;
            case DOWN:
                y += speed;
                break;
            case LEFT:
                x -= speed;
                break;
            case RIGHT:
                x += speed;
                break;
        }
    }

    @Override
    public void run() {
        while (isAlive) {
            move();

            if (x < -Constants.MISSILE_RADIUS || x > Constants.GAME_PANEL_WIDTH + Constants.MISSILE_RADIUS ||
                    y < -Constants.MISSILE_RADIUS || y > Constants.GAME_PANEL_HEIGHT + Constants.MISSILE_RADIUS) {
                isAlive = false;
                break;
            }
//            System.out.println("Missile x: " + x + " y: " + y);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    // 碰撞检测
    public boolean collidesWith(BaseTank tank) {
        Rectangle missileRect = new Rectangle(x, y, Constants.MISSILE_RADIUS, Constants.MISSILE_RADIUS);
        Rectangle tankRect = new Rectangle(tank.getX() - Constants.TANK_WIDTH / 2, tank.getY() - Constants.TANK_HEIGHT / 2, Constants.TANK_WIDTH, Constants.TANK_HEIGHT);
        return missileRect.intersects(tankRect);
    }

    public void draw(Graphics2D g) {
        g.setColor(color);
        g.fillOval(x - Constants.MISSILE_RADIUS / 2,
                y - Constants.MISSILE_RADIUS / 2, Constants.MISSILE_RADIUS,
                Constants.MISSILE_RADIUS);
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public boolean isAlive() {
        return isAlive;
    }

    public void setAlive(boolean alive) {
        isAlive = alive;
    }



    public Color getColor() {
        return color;
    }
}
